package com.example.husbandry_online.view;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.husbandry_online.R;
import com.example.husbandry_online.adapter.HomePageFragmentAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.lang.reflect.Field;

public class HomeFragment extends Fragment {
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    View root;

    public HomeFragment() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        root = inflater.inflate(R.layout.fragment_home, container, false);
        initView();
        initFragment();
        return root;
    }

    private void initView() {
        tabLayout = root.findViewById(R.id.tabLayout);
        viewPager2 = root.findViewById(R.id.viewPager2);
    }

//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        try {
//          Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
//          childFragmentManager.setAccessible(true);
//          childFragmentManager.set(this, null);
//        } catch (NoSuchFieldException e) {
//              throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//              throw new RuntimeException(e);
//        }
//    }

    private void initFragment() {
        viewPager2.setAdapter(new HomePageFragmentAdapter(this));
        //设置第二页为起始页
        viewPager2.setCurrentItem(1);
        TabLayoutMediator tab = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position){
                    case 0:
                        tab.setText(R.string.fragment1);
                        break;
                    case 1:
                        tab.setText(R.string.fragment2);
                        break;
                    case 2:
                        tab.setText(R.string.fragment3);
                        break;
                }
            }
        });
        tab.attach();
    }
}